/*
模块名称：处方打印
起始日期：2021-5-23
功能描述：
1.自动检索可打印处方，打印输出。
2.指定收据号进行处方打印。
业务逻辑：
1.
2.通过 invoice_no （发票号）查询 fin_opb_feedetail/sun_recipe_pr ,获取处方药品项目基本信息。
通过recipe_no（处方号） 关联 met_ord_recipedetail ,获取处方诊断,医师姓名
通过 clinic_code（门诊唯一编号）查询 fin_opr_register 获取处方头信息。

*/
#include "dialog_cfdy.h"
#include "ui_dialog_cfdy.h"
#include "pub_var.h"
#include <QSettings>
#include <QPrinter>
#include <QPrinterInfo>
#include <QDebug>
#include <QMessageBox>
#include <QMap>
#include <QMapIterator>
#include <QDate>
#include <QDateTime>
#include <QPen>
#include <QVector>
#include <QFontMetrics>
#include <QSqlError>
#include <QTextCodec>
#include <QFile>
#include <QImage>
#include <QBitmap>
#include <QColor>
#include <QComboBox>
#include <QAxWidget>

Dialog_cfdy::Dialog_cfdy(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog_cfdy)
{

    ui->setupUi(this);
    qrm = new QSqlQuery(pub::db_m);
    qro = new QSqlQuery(pub::db_o);
    qrot = new QSqlQuery(pub::db_o);

    QSettings setIni("clin.ini", QSettings::IniFormat);
    terminalCode = setIni.value("cfdy/terminal").toString();    //当前工作窗口代码

    //准备工作终端列表
    qro->exec("select t_name, t_code , dept_code from pha_sto_terminal where t_type = '0'");
    while(qro->next()){
        ui->cbbTerminal->addItem(qro->value(0).toString());
        if( qro->value(1).toString() == terminalCode ){
            terminalName = qro->value(0).toString();    //当前窗口代码对应的名称
            deptCode = qro->value(2).toString();    //
        }
    }

    //当前工作打印机
    cfPrinter = setIni.value("cfdy/printer").toString();

    bzPrinter = setIni.value("bz/printer").toString();

    //显示当前工作终端
    ui->cbbTerminal->setCurrentText(terminalName);

    //恢复当前窗口位置
    QRect rct = setIni.value("windowState/cfdy").toRect();
    this->setGeometry(rct);
    this->setWindowFlags(Qt::WindowMinimizeButtonHint | Qt::WindowCloseButtonHint);

    //接收默认事件的按钮不显示
    ui->pushButton->setVisible(false);

    //定时器，用于自动打印处方
    tm = new QTimer(this);
    connect(tm, SIGNAL(timeout()), this, SLOT(onTimerOut()));

    //打印机设置
    prt= new QPrinter(QPrinter::HighResolution); // :ScreenResolution  HighResolution
    prt->setPrinterName(cfPrinter);

    qrm->prepare("select p_width,p_height from com_printer_setting "
                 "where p_type = '处方' and p_item = '页面'");
    qrm->exec();
    int w = 0, h = 0;
    if(qrm->next()){
        w = qrm->value(0).toInt();
        h = qrm->value(1).toInt();
    }else{
        QMessageBox::information(this,"错误","处方打印参数缺失！");
    }

    if( w<30 || h<30 ){
        QMessageBox::information(this,"错误","处方打印参数错误：页面数据无效！");
        w = 130 ;
        h = 248;
    }
    //打印机修正参数。不同打印机以相同数据输出，实际大小有差异，以此参数修正
    float printerScale = setIni.value("cfdy/scale").toDouble();
    int dotPerInch = prt->physicalDpiX();
    ptScale = double(dotPerInch) / 25.4 * printerScale;

    //设置纸张大小
    QSizeF sz = QSizeF(w , h);
    QPageSize psz(sz, QPageSize::Millimeter, "mzcf", QPageSize::ExactMatch);//  ::FuzzyMatch);Millimeter
    prt->setPageSize(psz);


    prt->setOrientation(QPrinter::Portrait);      // 纵向打印
    prt->setFullPage(true);
    pnt = new QPainter();

    ui->lwYfy->setFont(this->font());
    ui->pbTf->setEnabled(false);    //退费
    ui->pbBldy->setEnabled(false);    //病历
    ui->pbSinglePrint->setEnabled(false);    //处方
    //connect(ui->twDpList, SIGNAL(itemClicked(QTableWidgetItem *)),this,SLOT(twDpList_Clicked(QTableWidgetItem *)));
    //connect(ui->cbbTerminal, SIGNAL(currentTextChanged(const QString &arg1)), this, SLOT(cbbTerminalTextChanged(const QString &arg1)));
    connect(ui->cbbTerminal, SIGNAL(currentTextChanged(QString)), this, SLOT(cbbTerminalTextChanged(QString)));
    count = 0;
}

Dialog_cfdy::~Dialog_cfdy()
{
    delete ui;
}

void Dialog_cfdy::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    tm->stop();
    QSettings setIni("clin.ini", QSettings::IniFormat);
    //setIni.setIniCodec(QTextCodec::codecForName("UTF_8"));
    setIni.setValue("windowState/cfdy", QVariant(this->geometry()));

    qro->exec("select t_code from pha_sto_terminal where t_name = '" + ui->cbbTerminal->currentText() + "'");
    if(qro->next()){
        terminalCode = qro->value(0).toString();        //科室代码
    }
    setIni.setValue("cfdy/terminal",terminalCode);
}

void Dialog_cfdy::cbbTerminalTextChanged(QString arg1)
{
    qro->exec("select t_code ,dept_code from pha_sto_terminal where t_name = '" + arg1 + "'");

    if(qro->next()){
        deptCode = qro->value(1).toString();
        terminalCode = qro->value(0).toString();        //科室代码
        terminalName = arg1;

        qDebug()<<terminalCode<<terminalName;
    }
}

void Dialog_cfdy::on_pbExit_clicked()
{
    close();
}

void Dialog_cfdy::on_pbSinglePrint_clicked()
{
    //通过 invoice_no （发票号）查询 fin_opb_feedetail,获取处方药品项目基本信息。
    qro->prepare("select item_name, specs, unit_price, qty, "
                 " use_name, frequency_code, dose_once, dose_unit, base_dose, "
                 " pack_qty, price_unit, recipe_no, clinic_code, invoice_no"
                 " from fin_opb_feedetail "
                 " where invoice_no = :invoice_no and drug_flag='1' and trans_type = '1'"
                 " order by recipe_no, sequence_no");
    qro->bindValue(":invoice_no", pub::add0(ui->leSjh->text().trimmed(),12));

    if(!qro->exec()){
        qDebug()<<"sql error!"<<qro->lastQuery();
        return;
    }

    if(!qro->next()){
        qDebug()<<"sql has no value."<<qro->lastQuery();
        QMessageBox::information(this,"错误","找不到指定的收据号！");
        return;
    }

    //数据表内容导入内存
    QList<QMap<QString,QString>> rec;
    QMap<QString,QString> mp;
    while(true){
        mp.clear();
        mp["item_name"] = qro->value(0).toString();
        mp["specs"] = qro->value(1).toString();
        mp["unit_price"] = qro->value(2).toString();
        mp["qty"] = qro->value(3).toString();   //数量
        mp["use_name"] = qro->value(4).toString();
        mp["frequency_code"] = qro->value(5).toString();
        mp["dose_once"] = qro->value(6).toString();
        mp["dose_unit"] = qro->value(7).toString();
        mp["base_dose"] = qro->value(8).toString();
        mp["pack_qty"] = qro->value(9).toString();  //包装数量
        mp["price_unit"] = qro->value(10).toString();  //划价单位 ， qty / pack_qty = 划价数量
        mp["recipe_no"] = qro->value(11).toString();
        mp["clinic_code"] = qro->value(12).toString();
        mp["invoice_no"] = qro->value(13).toString();
        rec << mp;
        if(!qro->next()){
            break;
        }
    }
    QString currentRecipeNo = "";//当前处方号
    QString newRecipeNo = "";//新处方号
    double costCount = 0;   //处方金额
    double days_pack; //包装可用天数
    double days_item; //品种可用天数
    double days_item_1; //数量大于1的品种，数量减1个零售包装之后的可用天数
    int currentLine = 1;    //当前项目行数，1 - 5
    pnt->begin(prt);
    mpPage.clear(); //清空页面数据

    int i = 0;

    while(true){
        newRecipeNo = rec[i]["recipe_no"] ;
        if(currentRecipeNo != newRecipeNo){ //处方号变更，提取处方头信息进行输出
            //首次进入循环时 currentRecipe_no 为空，此时不打印，只赋值
            if(!currentRecipeNo.isEmpty()){
                //非首次进入,打印前一张处方
                mpPage["金额"] = QString::asprintf("%.2f", costCount); //
                mpPage["recipe_no"] = rec[i-1]["recipe_no"];
                mpPage["clinic_code"] = rec[i-1]["clinic_code"];
                mpPage["invoice_no"] = rec[i-1]["invoice_no"];
                printPage();
                prt->newPage();     //处方号变更，换页
                mpPage.clear(); //清空页面数据
                currentLine = 1;    //行数
                costCount = 0;  //金额
            }
            currentRecipeNo = newRecipeNo;  //
            //通过recipe_no（处方号） 关联 met_ord_recipedetail ,获取处方诊断,医师姓名
            qro->prepare("select doct_name,clinicdiag_name,clinicotherdiag1_name,"
                         "clinicotherdiag2_name, doct_code from met_ord_recipedetail "
                         " where recipe_no = :recipe_no");
            qro->bindValue(":recipe_no", currentRecipeNo);//使用newRecipeNo
            if(!qro->exec()){
                QMessageBox::information(this,"error","从 met_ord_recipedetail 提取诊断信息错误!");
                qDebug()<<qro->lastQuery();
                break;
            }
            if(qro->next()){
                mpPage["医师"] = qro->value(0).toString();
                mpPage["doct_code"] = qro->value("doct_code").toString();
                QString s = qro->value(1).toString();
                if(!qro->value(2).toString().isEmpty()){
                    s = s +"," + qro->value(2).toString();
                }
                if(!qro->value(3).toString().isEmpty()){
                    s = s +"," + qro->value(3).toString();
                }
                mpPage["临床诊断"] = s;
            }else{
                QMessageBox::information(this,"error","无法从 met_ord_recipedetail 找到对应的信息!");
            }

            //通过 clinic_code（门诊唯一编号）查询 fin_opr_register 获取患者信息。
            //费别， 科室，日期，病志号，姓名，性别，年龄，
            qro->prepare("select pact_name, dept_name, trunc(reg_date) dt, card_no,"
                         "name, decode(sex_code , 'M', '男', 'F', '女') sex, birthday "
                         "from fin_opr_register where clinic_code = :cd");
            qro->bindValue(":cd",rec[i]["clinic_code"]);
            if(!qro->exec()){
                QMessageBox::information(this,"error","从 fin_opr_register 提取诊断信息错误!");
                qDebug()<<qro->lastQuery();
                break;
            }
            if(!qro->next()){
                QMessageBox::information(this,"error","从 fin_opr_register 找不到对应信息!");
                qDebug()<<qro->lastQuery();
                break;
            }

            mpPage["科别"] = qro->value("dept_name").toString();
            QDate dt = qro->value("dt").toDate();
            mpPage["日期"] = dt.toString("yyyy-MM-dd");
            mpPage["病志号"] = qro->value("card_no").toString();
            mpPage["姓名"] = qro->value("name").toString();
            mpPage["性别"] = qro->value("sex").toString();
            dt = qro->value("birthday").toDate();
qDebug()<<"dt : "<<dt;
            QStringList ag = pub::getNl(dt.toString("yyyy-MM-dd"));
            mpPage["年龄"] = ag[0] + ag[1];
            mpPage["处方标志"] = "普通";
            mpPage["费别"] = qro->value("pact_name").toString();
            mpPage["名头"] = pub::hos_name;
            mpPage["处方笺"] = "处 方 笺";

        }

        mpPage["品名" + QString::number(currentLine)] = rec[i]["item_name"] ;

        QString price1 = QString::asprintf("%.1f", rec[i]["unit_price"].toDouble()); //保留1位小数
        QString price2 = QString::asprintf("%.2f", rec[i]["unit_price"].toDouble()); //保留2位小数
        QString price0 = qFuzzyCompare(price1.toDouble(), price2.toDouble()) ? price1 : price2;
        //保留1位小数和2位小数数值相等，输出1位小数形式，否则输出2位小数形式

        mpPage["price" + QString::number(currentLine)] = price0;
        mpPage["规格" + QString::number(currentLine)] = rec[i]["specs"];
        QString sl, yfyl;       //品种数量，用法用量, 字串，供打印用
        int i_sl = rec[i]["qty"].toUInt() / rec[i]["pack_qty"].toInt() ;// 品种数量，数值，供计算用
        sl = QString::number(i_sl) + rec[i]["price_unit"];
        costCount = costCount + i_sl * rec[i]["unit_price"].toDouble();     //金额累计
        yfyl = "用法：";
        yfyl.append(rec[i]["dose_once"]);   //每次数量
        yfyl.append(rec[i]["dose_unit"]);   //数量单位
        yfyl.append("  ");
        qrm->prepare("select frequency_name, day_times from "
                     "com_dict_frequency where frequency_code = :code ");
        qrm->bindValue(":code",rec[i]["frequency_code"]);
        if(!qrm->exec()){
            QMessageBox::information(this,"错误", "查询 com_dict_frequency 失败。"+qrm->lastQuery());
        }
        if(!qrm->next()){
            QMessageBox::information(this,"错误","提取 com_dict_frequency 数据无效！" + qrm->lastQuery());
        }
        yfyl.append(qrm->value(0).toString());  //每日用量
        yfyl.append("  ");
        yfyl.append(rec[i]["use_name"]);    //用法
        double days = qrm->value(1).toDouble();    //每日次数
        days_pack = rec[i]["base_dose"].toDouble() * rec[i]["pack_qty"].toDouble()
                / rec[i]["dose_once"].toDouble() / days ;//最小包装可用天数
        days_item = days_pack * rec[i]["qty"].toDouble() / rec[i]["pack_qty"].toDouble(); //品种可用天数
        days_item_1 = days_item - days_pack; //减少一个包装之后的品种可用天数
        //qDebug()<<days_pack<<days_item;
        QString bz = "";
        if(i_sl == 1){//单包装,
            if(days_item > 7){//超门诊量
                bz.append("*不拆零");//最小包装即超量，按“不拆零”处理
            }
        }else{
            if(days_item > 30){//超慢病量
                if(days_item_1 > 30){
                    bz.append("*外出带药");
                }else{
                    bz.append("*慢病,不拆零");
                }
            }else{
                if(days_item > 7){//超门诊量
                    if(days_item_1 >= 7){
                        bz.append("*慢病用药");
                    }else{
                        bz.append("*不拆零");
                    }
                }
            }
        }
        mpPage["备注" + QString::number(currentLine)] = bz;
        mpPage["数量" + QString::number(currentLine)] = sl;
        mpPage["用法用量" + QString::number(currentLine)] = yfyl ;
        currentLine ++ ; //项目行数量加 1
        //下一行预填充，如有正常值，此填充将被覆盖
        mpPage["品名" + QString::number(currentLine)] = "***以下空白***";

        i++;
        if( i  == rec.length()){//循环结束
            mpPage["金额"] = QString::asprintf("%.2f", costCount);
            mpPage["recipe_no"] = rec[i-1]["recipe_no"];
            mpPage["clinic_code"] = rec[i-1]["clinic_code"];
            mpPage["invoice_no"] = rec[i-1]["invoice_no"];

            printPage();
            pnt->end(); //循环完成，结束当前页面
            break;
        }
    }
}


void Dialog_cfdy::printPage()
{
    QString item, mode,print_item,font;
    QFont ft=QFont();
    double top,left,width,height,size;
    int position;
    qrm->prepare("select p_type,p_item,p_top,p_left,p_width,p_height,"
                 "p_font_name,p_font_size,p_position,p_mode,p_print_item,"
                 "p_item_type from com_printer_setting where p_type = '处方'");
    if(!qrm->exec()){
        QMessageBox::information(this,"错误","读取处方格式数据表失败：" + qrm->lastQuery());
        return;
    }
    while(qrm->next()){
        if(qrm->value("p_item_type").toString() == "item"){
            item = qrm->value(1).toString();
            top = qrm->value(2).toDouble();
            left = qrm->value(3).toDouble();
            width = qrm->value(4).toDouble();
            height = qrm->value(5).toDouble();
            font = qrm->value(6).toString();
            size = qrm->value(7).toDouble();
            position = qrm->value(8).toInt();
            mode = qrm->value(9).toString();
            print_item = qrm->value(10).toString();
            item = mpPage.value(item);

            QString outText;    //输入文本
            if(mode == "1"){
                outText = print_item + "：" + item;
            }else if(mode == "0"){
                outText =  item;
            }else  if(mode == "3"){
                outText =  print_item ;
            }

            //QFontMetrics fm(font, prt);
            ft.setPixelSize(int(ptScale * size));
            ft.setFamily(font);
            QFontMetrics fm(ft, prt);
            int pixelsWide;
            if(item == "***以下空白***"){  //行无内容，缩小字号
                size = size * 0.8;
                left = 50;
            }else{
                pixelsWide = fm.width(outText);
                if(pixelsWide > width * ptScale){//超过预定格式，缩小字号
                    size = size * ( width * ptScale / pixelsWide );//
                }
            }

            ft.setPixelSize(int(ptScale * size));
            ft.setFamily(font);
            pnt->setFont(ft);

            const QRect rect = QRect( left * ptScale, top * ptScale, width * ptScale, height * ptScale);
            QRect boundingRect;

            pnt->drawText(rect, position, outText, &boundingRect);

            if(print_item.mid(0,2) == "品名"){    //品名字串，后面附加价格

                QString price = mpPage["price"+print_item.mid(2,1)];
                if(!price.isEmpty()){//价格字串存在
                    QFontMetrics fm1(ft, prt);
                    int pixelsWide = fm1.width(outText);
                    ft.setPixelSize(int(ptScale * size * 0.8)); //缩小字号
                    pnt->setFont(ft);
                    //                       品名字串左起点    +  品名字串宽度   +  半个字符
                    const QRect rect = QRect( left * ptScale + pixelsWide + (ptScale * size * 0.8) /2 ,
                                              ptScale *( top + size * 0.2) ,
                                              width * ptScale, height * ptScale);
                    pnt->drawText(rect, position, "￥" + price , &boundingRect);
                }
            }

        }else if(qrm->value("p_item_type").toString() == "line"){
            mode = qrm->value(9).toString();
            top = qrm->value(2).toInt() * ptScale;
            left = qrm->value(3).toInt() * ptScale;
            width = qrm->value(4).toInt() * ptScale;
            height = qrm->value(5).toInt() * ptScale;

            QPen p ;
            if(mode == "1"){
                QVector<qreal> dash;
                dash << 0.2 * ptScale << 1 * ptScale;
                p.setStyle(Qt::DotLine);
                //p.setStyle(Qt::DashDotLine);
                //p.setStyle(Qt::CustomDashLine);
                p.setWidth(0.1 * ptScale);
                p.setDashPattern(dash);
                pnt->setPen(p);
            }else{
                p.setStyle(Qt::SolidLine);
                p.setWidth(0.2 * ptScale);
                pnt->setPen(p);
            }

            pnt->drawLine(left,top,height,width);
        }else if(qrm->value("p_item_type").toString() == "pic"){

            item = mpPage.value(qrm->value(1).toString());
            top = qrm->value(2).toDouble();
            left = qrm->value(3).toDouble();
            width = qrm->value(4).toDouble();
            height = qrm->value(5).toDouble();
            const QRect rect = QRect( left * ptScale, top * ptScale, width * ptScale, height * ptScale);
            QFile f;
            QString fileName = "pics/" + item + ".png";

            if(f.exists(fileName) ){ //医师签字文件存在

                QPixmap pix;
                //QImage pix;
                pix.load(fileName);
                //pnt->fillRect(rect, Qt::transparent);
                pnt->drawImage(rect, pix.toImage());
            }else{
                QMessageBox::information(this,"注意","医师签名文件 " + fileName + " 不存在！");
            }
        }
    }
    savePrintStatus();
    processData(mpPage["recipe_no"]);
}
void Dialog_cfdy::savePrintStatus()
{
    //设置处方已打印标志
    QString str = "update sun_recipe_pr set print_flag = '1' where recipe_no= '" + mpPage["recipe_no"] + "'" ;
    qDebug() << "设置处方已打印标志: " << str;
    qro->exec(str);

}

void Dialog_cfdy::onTimerOut()
{
    if(ui->lb_status->text() == "◇◆"){
        ui->lb_status->setText("◆◇");
    }else{
        ui->lb_status->setText("◇◆");
    }

    if(timerCount++ > 10){//到达查询时间

        tm->stop();//暂停定时器
        qro->exec("select distinct invoice_no from sun_recipe_pr where drug_dept_code='"
                  + deptCode + "' and trans_type = '1' and print_flag = '0' ");

        QStringList invo;

        while(qro->next()){
            invo << qro->value(0).toString();
            qDebug()<<qro->value(0).toString();
        }

        QString invoice_no;
        foreach(invoice_no, invo){
            if(!invoice_no.isEmpty()){
                ui->leSjh->setText(invoice_no);
                on_pbSinglePrint_clicked();
            }
        }
        ui->leSjh->setText("");
        timerCount = 0;
        on_pbDisplay_clicked();    //显示已付药列表
        acceptListClicked = false;
        tm->start(500);//恢复定时器
    }
}

void Dialog_cfdy::on_pbDisplay_clicked()
{
    //显示已付药列表
    acceptListClicked = true;
    qro->prepare("select distinct invoice_no, card_no, name, opdt from ( "
                 "select  a.invoice_no, a.card_no, b.name, "
                 "to_char(a.oper_date,'yyyy-mm-dd hh24:mi:ss') opdt from "
                 "sun_recipe_pr a, fin_opr_register b "
                 "where trunc(a.oper_date) = trunc(sysdate) and "
                 "a.clinic_code = b.clinic_code) order by opdt desc");
    if(qro->exec()){
        ui->lwYfy->clear();
        while(qro->next()){
            QString t = qro->value(0).toString();
            t.append(" ");
            t.append(qro->value(3).toString());
            t.append(" ");
            t.append(qro->value(2).toString());
            ui->lwYfy->addItem(t);
        }
    }

}
void Dialog_cfdy::on_pbStop_clicked()
{
    tm->stop();
    //停止自动打印，允许手工打印
    ui->pbSinglePrint->setEnabled(true);
    ui->pbSearch->setEnabled(true);
    ui->leSjh->setEnabled(true);
    ui->pbDisplay->setEnabled(true);
    acceptListClicked = true;
}
void Dialog_cfdy::on_pbStart_clicked()
{
    //开始自动打印，禁止无关界面操作
    ui->lwYfy->clear();
    ui->pbSinglePrint->setEnabled(false);
    ui->pbTf->setEnabled(false);
    ui->pbBldy->setEnabled(false);
    ui->pbDisplay->setEnabled(false);
    ui->rbF->setChecked(true);
    ui->pbSearch->setEnabled(false);
    acceptListClicked = false;
    ui->leSjh->setEnabled(false);
    tm->start(500);

}

void Dialog_cfdy::processData(QString recipe_no)
{
    QList<QMap<QString,QString>> applyOutList;  //出库申请
    QList<QMap<QString,QString>> storageList;   //库存数据
    QMap<QString,QString> mp;
    //检索数据是否已经被处理
    qro->prepare("select recipe_no from pha_sto_recipe where  "
                 "RECIPE_STATE = '3' and recipe_no = :recipe_no");
    qro->bindValue(":recipe_no",recipe_no);
    if(!qro->exec()){
        QMessageBox::information(this,"error", qro->lastError().text());
        return;
    }
    if(qro->next()){
        qDebug()<<"recipe_no : "<< recipe_no << " , related data has been saved.";
        return; //已经做过数据处理
    }

    //update pha_sto_recipe 数据
    qro->prepare("update pha_sto_recipe set RECIPE_STATE = '3', DRUGED_QTY = RECIPE_QTY, "
                 "DRUGED_DATE = sysdate, SEND_DATE = sysdate, EXT_FLAG1 = :ext_flag1,"
                 "SEND_OPER = :SEND_OPER, DRUGED_OPER = :druged_oper "
                 " where recipe_no = :recipe_no");
    qro->bindValue(":ext_flag1", terminalCode);
    qro->bindValue(":SEND_OPER", pub::usr_code);
    qro->bindValue(":DRUGED_OPER", pub::usr_code);
    qro->bindValue(":recipe_no", recipe_no);
    qro->exec();

    if(!qro->exec()){
        QMessageBox::information(this,"return error", qro->lastError().text());
        return;
    }


    //临时保存 PHA_COM_APPLYOUT

    qro->prepare("SELECT * FROM PHA_COM_APPLYOUT WHERE "
                 " RECIPE_NO = :rcptn AND DRUG_DEPT_CODE = :dptcd AND CLASS3_MEANING_CODE = 'M1'"
                 " AND APPLY_STATE = '0' "
                 " order by comb_no,sequence_no");

    qro->bindValue(":dptcd", deptCode);
    qro->bindValue(":rcptn", recipe_no);
    if(!qro->exec()){
        QMessageBox::information(this,"error", qro->lastError().text());
        return;
    }
    //
    while(qro->next()){
        mp["APPLY_NUMBER"] = qro->value("APPLY_NUMBER").toString();//申请流水号
        mp["DEPT_CODE"] = qro->value("DEPT_CODE").toString();//申请部门编码（科室或者病区）
        mp["DRUG_DEPT_CODE"] = qro->value("DRUG_DEPT_CODE").toString();//发药部门编码
        mp["CLASS3_MEANING_CODE"] = qro->value("CLASS3_MEANING_CODE").toString();//出库申请分类
        mp["DRUG_CODE"] = qro->value("DRUG_CODE").toString();//药品编码
        mp["TRADE_NAME"] = qro->value("TRADE_NAME").toString();//药品商品名
        mp["DRUG_TYPE"] = qro->value("DRUG_TYPE").toString();//药品类别
        mp["SPECS"] = qro->value("SPECS").toString();//规格
        mp["PACK_UNIT"] = qro->value("PACK_UNIT").toString();//包装单位
        mp["PACK_QTY"] = qro->value("PACK_QTY").toString();//包装数
        mp["MIN_UNIT"] = qro->value("MIN_UNIT").toString();//最小单位
        mp["RETAIL_PRICE"] = qro->value("RETAIL_PRICE").toString();//零售价
        mp["APPLY_OPERCODE"] = qro->value("APPLY_OPERCODE").toString();//申请人编码
        QDateTime dt = qro->value("APPLY_DATE").toDateTime();
        mp["APPLY_DATE"] = dt.toString("yyyyMMddHHmmss");//申请日期
        mp["APPLY_STATE"] = qro->value("APPLY_STATE").toString();//申请状态 0申请，1核准（出库），2作废，3暂不摆药
        mp["APPLY_NUM"] = qro->value("APPLY_NUM").toString();//申请出库量(每付的总数量)
        mp["PATIENT_ID"] = qro->value("PATIENT_ID").toString();//患者编号
        mp["PATIENT_DEPT"] = qro->value("PATIENT_DEPT").toString();//患者科室
        mp["DRUGED_DEPT"] = qro->value("DRUGED_DEPT").toString();//摆药科室
        mp["DRUGED_EMPL"] = qro->value("DRUGED_EMPL").toString();//摆药人
        dt = qro->value("DRUGED_DATE").toDateTime();
        mp["DRUGED_DATE"] = dt.toString("yyyyMMddHHmmss");//摆药日期
        mp["DOSE_ONCE"] = qro->value("DOSE_ONCE").toString();//每次剂量
        mp["DOSE_UNIT"] = qro->value("DOSE_UNIT").toString();//剂量单位
        mp["USAGE_CODE"] = qro->value("USAGE_CODE").toString();//用法代码
        mp["USE_NAME"] = qro->value("USE_NAME").toString();//用法名称
        mp["DFQ_FREQ"] = qro->value("DFQ_FREQ").toString();//频次代码
        mp["DFQ_CEXP"] = qro->value("DFQ_CEXP").toString();//频次名称
        mp["DOSE_MODEL_CODE"] = qro->value("DOSE_MODEL_CODE").toString();//剂型编码
        mp["MO_ORDER"] = qro->value("MO_ORDER").toString();//医嘱流水号
        mp["COMB_NO"] = qro->value("COMB_NO").toString();//组合序号
        mp["RECIPE_NO"] = qro->value("RECIPE_NO").toString();//处方号
        mp["SEQUENCE_NO"] = qro->value("SEQUENCE_NO").toString();//处方内项目流水号
        mp["VALID_STATE"] = qro->value("VALID_STATE").toString();//有效状态（0有效，1无效，2不摆药）
        applyOutList << mp;
        mp.clear();
    }
    qDebug()<<"applyOutList.length"<<applyOutList.length();

    //update PHA_COM_APPLYOUT
    qro->prepare(" UPDATE PHA_COM_APPLYOUT"
                 " SET APPLY_STATE = '2', DRUGED_DEPT = DRUG_DEPT_CODE, DRUGED_EMPL = :empl,"
                 " DRUGED_DATE = sysdate, DRUGED_NUM = 0, OUT_BILL_CODE = '0' "
                 " WHERE DRUG_DEPT_CODE = :dept AND CLASS3_MEANING_CODE = 'M1' "
                 " AND RECIPE_NO = :rcn");
    qro->bindValue(":dept", deptCode);
    qro->bindValue(":empl", pub::usr_code);
    qro->bindValue(":rcn", recipe_no);
    if(!qro->exec()){
        QMessageBox::information(this,"Error in update pha_com_applyout", qro->lastError().text());
        return;
    }

    //INSERT pha_com_output
    foreach(mp, applyOutList){
        //查询药品库存表PHA_COM_STORAGE，提取有效库存数据
        qro->prepare("SELECT * FROM PHA_COM_STORAGE WHERE DRUG_DEPT_CODE = :dptcd "
                     " AND store_sum > 0 and DRUG_CODE = :drcd AND Valid_Flag = '1' "
                     //东软应用使用效期优先， 本应用使用批次优先。
                     " Order by to_number(group_code),VALID_DATE ");
        qro->bindValue(":dptcd", deptCode);
        qro->bindValue(":drcd", mp["DRUG_CODE"]);
        if(!qro->exec()){
            QMessageBox::information(this,"error", qro->lastError().text());
            return;
        }

        while(qro->next()){
            QMap<QString, QString> m;
            m["DRUG_DEPT_CODE"] = qro->value("DRUG_DEPT_CODE").toString();//库存科室 0-全部部门
            m["DRUG_CODE"] = qro->value("DRUG_CODE").toString();//药品编码
            m["GROUP_CODE"] = qro->value("GROUP_CODE").toString();//批次号
            m["BATCH_NO"] = qro->value("BATCH_NO").toString();//批号
            m["TRADE_NAME"] = qro->value("TRADE_NAME").toString();//药品商品名
            m["SPECS"] = qro->value("SPECS").toString();//规格
            m["DRUG_TYPE"] = qro->value("DRUG_TYPE").toString();//药品类别
            m["DRUG_QUALITY"] = qro->value("DRUG_QUALITY").toString();//药品性质
            m["RETAIL_PRICE"] = qro->value("RETAIL_PRICE").toString();//零售价
            m["WHOLESALE_PRICE"] = qro->value("WHOLESALE_PRICE").toString();//批发价
            m["PURCHASE_PRICE"] = qro->value("PURCHASE_PRICE").toString();//实进价
            m["PACK_UNIT"] = qro->value("PACK_UNIT").toString();//包装单位
            m["PACK_QTY"] = qro->value("PACK_QTY").toString();//包装数
            m["MIN_UNIT"] = qro->value("MIN_UNIT").toString();//最小单位
            m["SHOW_FLAG"] = qro->value("SHOW_FLAG").toString();//显示的单位标记
            QDateTime dt = qro->value("VALID_DATE").toDateTime();
            m["VALID_DATE"] = dt.toString("yyyyMMddHHmmss");//有效期
            m["STORE_SUM"] = qro->value("STORE_SUM").toString();//库存数量
            m["STORE_COST"] = qro->value("STORE_COST").toString();//库存金额
            m["PREOUT_SUM"] = qro->value("PREOUT_SUM").toString();//预扣库存数量
            m["PREOUT_COST"] = qro->value("PREOUT_COST").toString();//预扣库存金额
            m["VALID_FLAG"] = qro->value("VALID_FLAG").toString();//有效性标志 0 在用 1 停用 2 废弃
            m["PRODUCER_CODE"] = qro->value("PRODUCER_CODE").toString();//生产厂家
            m["LAST_MONTH_NUM"] = qro->value("LAST_MONTH_NUM").toString();//最近一次月结的库存量
            m["PLACE_CODE"] = qro->value("PLACE_CODE").toString();//货位号
            m["STATE"] = qro->value("STATE").toString();//在库状态（0-暂入库，1正式入库）
            m["MARK"] = qro->value("MARK").toString();//备注
            m["OPER_CODE"] = qro->value("OPER_CODE").toString();//操作员
            m["OPER_DATE"] = qro->value("OPER_DATE").toString();//操作日期
            m["INVOICE_NO"] = qro->value("INVOICE_NO").toString();//发票号
            m["ARK_FLAG"] = qro->value("ARK_FLAG").toString();//'是否药柜管理药品 1 药柜管理 0 非药柜管理';
            m["ARK_QTY"] = qro->value("ARK_QTY").toString();//药柜管理库存汇总数量
            storageList << m;
        }

        //处理库存数据消耗
        QMap<QString,QString> sto;
        int aplNum = mp["APPLY_NUM"].toInt();   //申请出库数量
        int opNum;                              //本批次出库数量
        foreach(sto ,storageList){
            int stoNum = sto["STORE_SUM"].toInt();  //本批次库存数量

            if(aplNum <= stoNum){       //库存数量允许出库
                opNum = aplNum;     //出库数量 = 申请数量
            }else{                      //申请数量大于库存数量
                opNum = stoNum;     //出库数量 = 库存数量
            }
            qro->exec("select SEQ_PHA_OUTBILL_ID.NEXTVAL from dual");
            qro->next();
            QString OUT_BILL_CODE = qro->value(0).toString();

            qro->prepare("INSERT INTO pha_com_output (DRUG_DEPT_CODE ,OUT_BILL_CODE ,SERIAL_CODE ,"
                         "GROUP_CODE , OUT_LIST_CODE ,OUT_TYPE ,CLASS3_MEANING_CODE ,IN_BILL_CODE ,"
                         "IN_SERIAL_CODE ,IN_LIST_CODE ,DRUG_CODE , TRADE_NAME ,DRUG_TYPE ,"
                         "DRUG_QUALITY ,SPECS ,PACK_UNIT ,PACK_QTY ,MIN_UNIT ,SHOW_FLAG , "
                         "SHOW_UNIT ,BATCH_NO , VALID_DATE , PRODUCER_CODE ,COMPANY_CODE ,"
                         "RETAIL_PRICE ,WHOLESALE_PRICE ,PURCHASE_PRICE , OUT_NUM ,SALE_COST ,"
                         "TRADE_COST ,APPROVE_COST ,STORE_NUM , STORE_COST ,SPECIAL_FLAG ,"
                         "OUT_STATE ,APPLY_NUM ,APPLY_OPERCODE ,APPLY_DATE ,EXAM_NUM ,EXAM_OPERCODE ,"
                         "EXAM_DATE ,APPROVE_OPERCODE ,APPROVE_DATE ,PLACE_CODE ,RETURN_NUM ,"
                         "DRUGED_BILL ,MED_ID ,DRUG_STORAGE_CODE , RECIPE_NO ,SEQUENCE_NO ,"
                         "GET_PERSON ,MARK ,OPER_CODE , OPER_DATE,ARK_FLAG,ARK_BILL_CODE,OUT_DATE"
                         ") VALUES ("
                         ":DRUG_DEPT_CODE ,:OUT_BILL_CODE ,1 ,:GROUP_CODE , '' ,'M1' ,'M1' ,0 ,0 ,'',"
                         ":DRUG_CODE , :TRADE_NAME ,:DRUG_TYPE ,:DRUG_QUALITY ,:SPECS ,:PACK_UNIT ,"
                         ":PACK_QTY ,:MIN_UNIT ,'0' , '' ,:BATCH_NO , :VALID_DATE ,:PRODUCER_CODE ,"
                         "(select  t.company_code from pha_com_input t where t.drug_dept_code = :DRUG_DEPT_CODE"
                         " and t.drug_code = :DRUG_CODE and t.group_code = :GROUP_CODE and rownum  = 1),"
                         ":RETAIL_PRICE ,0 ,:PURCHASE_PRICE , :OUT_NUM ,"
                         "(:OUT_NUM/:PACK_QTY)*:RETAIL_PRICE ,0 ,(:OUT_NUM/:PACK_QTY)*:PURCHASE_PRICE,"
                         ":STORE_NUM ,0 ,'0' ,'2' ,0 "
                         ",:APPLY_OPERCODE , SYSDATE ,:EXAM_NUM ,:EXAM_OPERCODE ,SYSDATE ,'' , SYSDATE ,"
                         "'' ,0 ,'0' ,'' ,:DRUG_STORAGE_CODE , :RECIPE_NO ,:SEQUENCE_NO ,:GET_PERSON ,"
                         "'' ,:OPER_CODE ,SYSDATE,'0',0,SYSDATE )");

            qro->bindValue(":DRUG_DEPT_CODE", deptCode);//出库科室编码
            qro->bindValue(":OUT_BILL_CODE",OUT_BILL_CODE);
            qro->bindValue(":GROUP_CODE", sto["GROUP_CODE"]);//批次号
            qro->bindValue(":DRUG_CODE", sto["DRUG_CODE"]);//药品编码
            qro->bindValue(":TRADE_NAME", sto["TRADE_NAME"]);//药品商品名
            qro->bindValue(":DRUG_TYPE", sto["DRUG_TYPE"]);//药品类别
            qro->bindValue(":DRUG_QUALITY", sto["DRUG_QUALITY"]);//药品性质
            qro->bindValue(":SPECS", sto["SPECS"]);//规格
            qro->bindValue(":PACK_UNIT", sto["PACK_UNIT"]);//包装单位
            qro->bindValue(":PACK_QTY", sto["PACK_QTY"]);//包装数
            qro->bindValue(":MIN_UNIT", sto["MIN_UNIT"]);//最小单位
            qro->bindValue(":BATCH_NO", sto["BATCH_NO"]);//批号
            QDateTime dt = QDateTime::fromString(sto["VALID_DATE"],"yyyyMMddhhmmss");
            qro->bindValue(":VALID_DATE", dt);//有效期
            qro->bindValue(":PRODUCER_CODE", sto["PRODUCER_CODE"]);//生产厂家
            //qro->bindValue(":COMPANY_CODE", sto["COMPANY_CODE"]);//供货单位代码
            qro->bindValue(":RETAIL_PRICE", sto["RETAIL_PRICE"]);//零售价
            //qro->bindValue(":WHOLESALE_PRICE", sto["WHOLESALE_PRICE"]);//批发价
            qro->bindValue(":PURCHASE_PRICE", sto["PURCHASE_PRICE"]);//购入价
            qro->bindValue(":OUT_NUM", opNum);//出库数量
            //qro->bindValue(":SALE_COST","SALE_COST");//零售金额
            //qro->bindValue(":APPROVE_COST",":APPROVE_COST");//购入金额
            qro->bindValue(":STORE_NUM", stoNum - opNum);//出库后库存数量
            //qro->bindValue(":STORE_COST",":STORE_COST");//出库后库存总金额
            qro->bindValue(":APPLY_OPERCODE", mp["APPLY_OPERCODE"]);//申请出库人
            qro->bindValue(":EXAM_NUM", opNum);//审批数量
            qro->bindValue(":EXAM_OPERCODE", pub::usr_code);//审批人
            qro->bindValue(":DRUG_STORAGE_CODE",mp["DEPT_CODE"]);//领药单位编码
            qro->bindValue(":RECIPE_NO", mp["RECIPE_NO"]);//处方号
            qro->bindValue(":SEQUENCE_NO", mp["SEQUENCE_NO"]);//处方流水号
            qro->bindValue(":GET_PERSON",mp["PATIENT_ID"]);//领药人,  clinic_code
            qro->bindValue(":OPER_CODE", pub::usr_code);//操作员
            if(!qro->exec()){
                QMessageBox::information(this,"error", qro->lastError().text());
                qDebug()<<"insert pha_com_output error."<<qro->lastQuery();
                return;
            }
            //核减库存
            qro->prepare("UPDATE PHA_COM_STORAGE SET STORE_SUM = STORE_SUM - :out_num,"
                         "STORE_COST = STORE_COST - :out_num / pack_qty * RETAIL_PRICE, "
                         "BILL_CODE = :bill_code, SERIAL_CODE = 0, TARGET_DEPT = :target_dept, "
                         "CLASS2_CODE = '0320|M1', OPER_CODE   = :oper_code, OPER_DATE   = SYSDATE"
                         " WHERE  DRUG_DEPT_CODE = :drug_dept_code AND DRUG_CODE  = :drug_code"
                         " AND GROUP_CODE = :group_code ");
            qro->bindValue(":out_num", opNum);
            qro->bindValue(":bill_code", OUT_BILL_CODE);
            qro->bindValue(":target_dept" ,mp["DEPT_CODE"]);
            qro->bindValue(":oper_code", pub::usr_code);
            qro->bindValue(":drug_dept_code", deptCode);
            qro->bindValue(":drug_code", sto["DRUG_CODE"]);
            qro->bindValue(":group_code", sto["GROUP_CODE"]);

            if(!qro->exec()){
                QMessageBox::information(this,"error", qro->lastError().text());
                qDebug()<<"update pha_com_storage error."<<qro->lastQuery();
                return;
            }

            //update fin_opb_feedetail
            qro->prepare("update fin_opb_feedetail set CONFIRM_FLAG = '1',"
                         " CONFIRM_CODE = :CONFIRM_CODE, CONFIRM_DEPT = :CONFIRM_DEPT, CONFIRM_DATE = sysdate, "
                         " NOBACK_NUM = 0, CONFIRM_NUM = QTY"
                         " where RECIPE_NO = :RECIPE_NO and MO_ORDER = :MO_ORDER and cancel_flag = '1'");
            qro->bindValue(":CONFIRM_CODE", pub::usr_code);
            qro->bindValue(":CONFIRM_DEPT", deptCode);
            qro->bindValue(":RECIPE_NO", mp["RECIPE_NO"]);
            qro->bindValue(":MO_ORDER", mp["MO_ORDER"]);
            if(!qro->exec()){
                QMessageBox::information(this,"error", qro->lastError().text());
                qDebug()<<"update fin_opb_feedetail error "<<qro->lastError().text();
                qDebug()<<qro->lastQuery();
                qDebug()<<pub::usr_code<<deptCode<<mp["RECIPE_NO"]<<mp["MO_ORDER"];
                return;
            }

            aplNum = aplNum - opNum;    //申请数量 = 申请数量 - 已完成数量
            if(aplNum == 0){    //申请数量已经完成，退出循环
                break;
            }
        }
        storageList.clear();
    }
}

void Dialog_cfdy::on_pushButton_clicked()
{
//    processData("2391861");

}

void Dialog_cfdy::on_lwYfy_clicked(const QModelIndex &index)
{
//    qDebug()<<index;
    if(!acceptListClicked){     //当前流程忽略单击
        return;
    }
    if(ui->rbF->isChecked() ){    //发票检索状态
        ui->leSjh->setText(pub::getStr(ui->lwYfy->item(index.row())->text()," ",1));
    }else{  //病志号检索
        clinicCode = pub::getStr(ui->lwYfy->item(index.row())->text()," ",4);
        ui->pbBldy->setEnabled(true);
//        ui->pbSinglePrint->setEnabled(true);    //处方
    }

}

void Dialog_cfdy::on_lwYfy_doubleClicked(const QModelIndex &index)
{
    QString sq, txt, card_no, clinicCode;

    txt = pub::getStr(ui->lwYfy->item(index.row())->text()," ",1);

    if(txt.indexOf("-") < 0){   //字串不包含"-"，有可能是发票号

        bool o;
        int i = txt.mid(0,1).toInt( &o);

        if(o){  //字串不包含"-"，首字符为数字，按发票方式检索
            sq = "select card_no, clinic_code from fin_opb_invoiceinfo where invoice_no = '" + txt + "'";
            qrot->exec(sq);
            qrot->next();
            card_no = qrot->value(0).toString();
            clinicCode = qrot->value(1).toString();
        }else{
            //非数字，当前状态不可检索
            return;
        }

    }else {
        bool o;
        int i = txt.mid(0,1).toInt( &o);

        if(o){  //转换成功，数字字串。当前状态为姓名或病志号检索
            clinicCode = pub::getStr(ui->lwYfy->item(index.row())->text()," ",4);
            sq = "select card_no from fin_opr_register where clinic_code = '" + clinicCode + "'";
            qrot->exec(sq);
            qrot->next();
            card_no = qrot->value(0).toString();
        }else{
            return;
        }
    }

    sq="select r.hzzs,r.xbs,r.jws,r.tgjc,r.yz,r.ys ,r.atinc , l.xmmc, l.xmjg, p.lxdh ,r.zd1,r.zd2,r.zd3"
       " from ys_bz_e_rec r, ys_bz_e_main m, ys_bz_e_lib l, ys_bz_e_patient_info p"
       " where m.atinc = r.id and  r.rq=curdate() and m.bzh='" + card_no + "'"
       " and l.id=r.id and m.patient_id=p.atinc";

    qrm->exec(sq);

    txt = "";

    bool hasDiag = true;
    bool hasRecipe = true;

    if(!qrm->next()){
        hasDiag = false;
//        QMessageBox::information(this,"注意","找不到关联的诊断信息！");
//        return;

    }else{
        txt.append("主诉：" + qrm->value("hzzs").toString() + "\n\r");
        txt.append("现病史：" + qrm->value("xbs").toString() + "\n\r");
        txt.append("既往史：" + qrm->value("jws").toString() + "\n\r");
        txt.append("检查：" + qrm->value("tgjc").toString() + "\n\r");
        QString zd = qrm->value("zd1").toString();
        if(!qrm->value("zd2").toString().isEmpty()){
            zd.append(", " + qrm->value("zd2").toString());
        }
        if(!qrm->value("zd3").toString().isEmpty()){
            zd.append(", " + qrm->value("zd3").toString());
        }
        txt.append("诊断：" + zd + "\n\r");
        txt.append("医嘱：" + qrm->value("yz").toString() );

    }
    sq = "select item_name, specs, qty/pack_qty qqty , price_unit, qty/pack_qty * unit_price , cancel_flag, CONFIRM_CODE, "
         " (select empl_name from com_employee where empl_code = f.doct_code and rownum = 1) "
         " from fin_opb_feedetail f where clinic_code ='"
         + clinicCode + "' and drug_flag = '1' and trans_type = '1' ";

    qrot->exec(sq);
    if(!qrot->next()){
        //QMessageBox::information(this,"注意","找不到关联的处方信息！");
        hasRecipe = false;
    }else{

        QString t_status, t_line;
        while(true){
            t_status = "";
            if(qrot->value(5).toString() == "0"){
                t_status = "已退费";
            }
            if(qrot->value(6).toString().isEmpty()){
                t_status = "未付药";
            }

            t_line = qrot->value(7).toString();
            t_line.append(" ");
            t_line.append(qrot->value(0).toString());
            t_line.append(" ");
            t_line.append(qrot->value(1).toString());
            t_line.append(" ");
            t_line.append(qrot->value(2).toString());
            t_line.append(" ");
            t_line.append(qrot->value(3).toString());
            t_line.append(" ");
            t_line.append(QString::asprintf("%.2f",qrot->value(4).toDouble())+"元");
            t_line.append(" " + t_status);
            txt.append("\n" + t_line);
            if(!qrot->next()){
                break;
            }
        }

    }
    if(hasDiag || hasRecipe){
        QMessageBox::information(this,"病志信息", txt);
    }else{
        QMessageBox::information(this,"注意","找不到关联的诊断和处方信息！");
    }

}

void Dialog_cfdy::on_leSjh_returnPressed()
{
    on_pbSearch_clicked();
}

void Dialog_cfdy::on_pbSearch_clicked()
{
    QString sq ;
    clinicCode = "";    //
    ui->pbTf->setEnabled(false);    //退费
    ui->pbBldy->setEnabled(false);    //病历
    ui->pbSinglePrint->setEnabled(false);    //处方
    ui->lwYfy->clear();
    if(ui->rbF->isChecked()){   //发票检索

        acceptListClicked = false;
        QString invo_no = pub::add0(ui->leSjh->text().trimmed(),12);
        qro->prepare("select item_name, specs, qty/pack_qty qqty , price_unit, "
                     "qty/pack_qty * unit_price , cancel_flag, CONFIRM_CODE,clinic_code ,"
                     "(select empl_name from com_employee where empl_code = f.doct_code and rownum = 1)"
                     " from fin_opb_feedetail f where invoice_no ='" + invo_no +
                     "' and drug_flag = '1' and trans_type = '1' ");

        if(!qro->exec()){
            qDebug()<<qro->lastError().text();
            qDebug()<<qro->lastQuery();
            qDebug()<<invo_no;
        }

        double count = 0;
        QString t;
        if(!qro->next()){
            QMessageBox::information(this,"错误","找不到指定的发票号码！");
            return;
        }
        clinicCode = qro->value(7).toString();
        doctName = qro->value(8).toString();
        QMessageBox:: StandardButton result;

        while(true){
            if(qro->value(5).toString() == "0"){

                result = QMessageBox::warning(NULL, "注意", "此发票已经退费，是否打印退费清单？",QMessageBox::Yes|QMessageBox::No);
                if(result == QMessageBox::Yes){
                    tfPrint();
                }
                return;
            }
            if(qro->value(6).toString().isEmpty()){
                QMessageBox::information(this,"错误","此发票未付药！");
                return;
            }
            t = qro->value(8).toString();
            t.append(" ");
            t.append(qro->value(0).toString());
            t.append(" ");
            t.append(qro->value(1).toString());
            t.append(" ");
            t.append(qro->value(2).toString());
            t.append(" ");
            t.append(qro->value(3).toString());
            t.append(" ");
            t.append(QString::asprintf("%.2f",qro->value(4).toDouble())+"元");
            ui->lwYfy->addItem(t);
            count = count + qro->value(4).toDouble();
            if(!qro->next()){
                break;
            }
        }

        ui->lwYfy->addItem("合计金额: " + QString::asprintf("%.2f", count));
        ui->pbTf->setEnabled(true);
        ui->pbBldy->setEnabled(true);
        ui->pbSinglePrint->setEnabled(true);    //处方

        qrot->exec("select pact_name, oper_date from fin_opb_invoiceinfo where invoice_no = '" + invo_no + "'");
        qrot->next();

        if( qrot->value(0).toString() != "现金"){  //非现金，有退费时限
            QDateTime dt1 = qrot->value(1).toDateTime();
            QDateTime dt2 = QDateTime::currentDateTime();
            int ct = dt1.daysTo(dt2);
            if(ct > 4){
                QMessageBox::information(this, "注意", "此发票为医保支付费且已超过时限，请谨慎操作！");
            }
        }
    }else if(ui->rbB->isChecked()){   //病志检索
        sq = "select to_char(reg_date,'yyyy-mm-dd hh24:mi:ss'), dept_name, clinic_code from fin_opr_register"
                     " where card_no = '" + pub::add0(ui->leSjh->text().trimmed(),10)+ "' order by reg_date";

    }else if(ui->rbX->isChecked()){   //姓名检索
        sq = "select to_char(reg_date,'yyyy-mm-dd hh24:mi:ss'), dept_name, clinic_code from fin_opr_register"
                     " where name = '" + ui->leSjh->text().trimmed()+ "' order by reg_date";
    }

    if(ui->rbX->isChecked() || ui->rbB->isChecked()){
        if(!qro->exec(sq)){
            QMessageBox::information(this, "error", qro->lastError().text());
            qDebug()<< qro->lastError().text();
            qDebug()<<qro->lastQuery();
            return;
        }
        if(!qro->next()){
            QMessageBox::information(this, "注意", "找不到指定的病历号或患者姓名！");
            qDebug()<<qro->lastQuery();
            return;
        }
        QString t;
        while(true){
            t = qro->value(0).toString();
            t.append(" ");
            t.append(qro->value(1).toString());
            t.append(" ");
            t.append(qro->value(2).toString());

            ui->lwYfy->addItem(t);

            if(!qro->next()){
                break;
            }
        }
        acceptListClicked = true;  //
    }

}

void Dialog_cfdy::on_pbTf_clicked()
{
    QMessageBox:: StandardButton result= QMessageBox::warning(NULL, "注意", "确定要对此发票号进行退费操作？",QMessageBox::Yes|QMessageBox::No);
    if(result == QMessageBox::No){
        return;
    }
    QString invo_no = pub::add0(ui->leSjh->text().trimmed(),12);
    QString recipe = "'recipe'";
    QString sq;


    sq = "select RECIPE_NO FROM MET_NUI_CANCELITEM where recipe_no in (SELECT RECIPE_NO from fin_opb_feedetail"
         " where invoice_no ='" + invo_no + "') ";
    if(!qro->exec(sq)){
        QMessageBox::information(this,"error", "error at selec recipe_no from met_nui_cancelitem "+qro->lastError().text());
        return;
    }
    if(qro->next()){
        result = QMessageBox::warning(NULL, "注意", "此发票已经退费，是否打印退费清单？",QMessageBox::Yes|QMessageBox::No);
        if(result == QMessageBox::Yes){
            tfPrint();
        }
        return;
    }

    sq = "SELECT CLINIC_CODE, reg_dpcd DEPT_CODE ,ITEM_CODE ,ITEM_NAME ,SPECS ,"
         " unit_price  SALE_PRICE ,qty QUANTITY ,PRICE_UNIT ,EXEC_DPCD , OPER_CODE ,RECIPE_NO ,SEQUENCE_NO ,"
         "invoice_no BILL_NO , pack_qty QTY,card_NO  from fin_opb_feedetail where invoice_no ='" + invo_no + "' ";
    if(!qro->exec(sq)){
        QMessageBox::information(this,"error", qro->lastError().text());
        qDebug()<<qro->lastQuery();
        qDebug()<<invo_no;
        return;
    }
qDebug()<<invo_no;
    while(qro->next()){
        recipe.append(",'" +  qro->value("RECIPE_NO").toString() + "'");

        qrot->prepare("INSERT INTO MET_NUI_CANCELITEM(APPLY_NO,INPATIENT_NO ,BABY_FLAG ,DEPT_CODE ,"
                     "DRUG_FLAG ,ITEM_CODE ,ITEM_NAME ,SPECS ,SALE_PRICE ,QUANTITY , DAYS ,PRICE_UNIT ,"
                     "EXEC_DPCD ,OPER_CODE ,RECIPE_NO , SEQUENCE_NO ,BILL_NO ,CONFIRM_FLAG ,CHARGE_FLAG ,QTY,card_NO)"
                     " values"
                     " ( SEQ_MET_NUI_CANCELITEM_ID.NEXTVAL ,:INPATIENT_NO , '0',:DEPT_CODE ,'1',"
                     ":ITEM_CODE ,:ITEM_NAME ,:SPECS , :SALE_PRICE ,:QUANTITY ,1,:PRICE_UNIT ,:EXEC_DPCD ,"
                     " :OPER_CODE ,:RECIPE_NO ,:SEQUENCE_NO ,:BILL_NO , '1','0',:QTY,:card_NO )"
                     );
        qrot->bindValue(":INPATIENT_NO", qro->value("CLINIC_CODE").toString());
        qrot->bindValue(":DEPT_CODE", qro->value("DEPT_CODE").toString());
        qrot->bindValue(":ITEM_CODE", qro->value("ITEM_CODE").toString());
        qrot->bindValue(":ITEM_NAME", qro->value("ITEM_NAME").toString());
        qrot->bindValue(":SPECS", qro->value("SPECS").toString());
        qrot->bindValue(":SALE_PRICE", qro->value("SALE_PRICE").toDouble());
        qrot->bindValue(":QUANTITY", qro->value("QUANTITY").toInt());
        qrot->bindValue(":PRICE_UNIT", qro->value("PRICE_UNIT").toString());
        qrot->bindValue(":EXEC_DPCD", qro->value("EXEC_DPCD").toString());
        qrot->bindValue(":OPER_CODE", qro->value("OPER_CODE").toString());
        qrot->bindValue(":RECIPE_NO", qro->value("RECIPE_NO").toString());
        qrot->bindValue(":SEQUENCE_NO", qro->value("SEQUENCE_NO").toString());
        qrot->bindValue(":BILL_NO", qro->value("BILL_NO").toString());
        qrot->bindValue(":QTY", qro->value("QTY").toInt());
        qrot->bindValue(":card_NO", qro->value("card_NO").toString());
        if(!qrot->exec()){
            QMessageBox::information(this,"error", "error at insert met_nui_cancelitem "+qrot->lastError().text());
            qDebug()<<qrot->lastQuery();
            qDebug()<<qro->value("CLINIC_CODE").toString();
            qDebug()<<qro->value("DEPT_CODE").toString();
            qDebug()<<qro->value("ITEM_CODE").toString();
            qDebug()<<qro->value("ITEM_NAME").toString();
            qDebug()<<qro->value("SPECS").toString();
            qDebug()<<qro->value("SALE_PRICE").toDouble();
            qDebug()<<qro->value("QUANTITY").toInt();
            qDebug()<<qro->value("PRICE_UNIT").toString();
            qDebug()<<qro->value("EXEC_DPCD").toString();
            qDebug()<<qro->value("OPER_CODE").toString();
            qDebug()<<qro->value("RECIPE_NO").toString();
            qDebug()<<qro->value("SEQUENCE_NO").toString();
            qDebug()<<qro->value("BILL_NO").toString();
            qDebug()<<qro->value("QTY").toInt();
            qDebug()<<qro->value("card_NO").toString();
            return;
        }
    }
qDebug()<<"MET_NUI_CANCELITEM";
    sq = "select drug_code,out_num,sale_cost,group_code,drug_storage_code,drug_dept_code"
         " from pha_com_output where recipe_no in(" + recipe + ")";
    if(!qro->exec(sq)){
        QMessageBox::information(this,"error", qro->lastError().text());
        qDebug()<<qro->lastQuery();
        qDebug()<<recipe;
        return;
    }
    while(qro->next()){
        qrot->prepare("UPDATE PHA_COM_STORAGE SET STORE_SUM = STORE_SUM + :qty, "
                      "STORE_COST = STORE_COST + :qty / pack_qty * retail_price, BILL_CODE = :invo_no, SERIAL_CODE = 1, "
                      "TARGET_DEPT = :tdept, CLASS2_CODE = '0320|M2', OPER_CODE = :oper, OPER_DATE   = SYSDATE  "
                      " WHERE  DRUG_DEPT_CODE = :ddept AND DRUG_CODE  = :drug_code AND GROUP_CODE = :grp ");
        qrot->bindValue(":invo_no", invo_no);
        qrot->bindValue(":qty", qro->value("out_num").toInt() );
        qrot->bindValue(":tdept", qro->value("drug_storage_code").toString());
        qrot->bindValue(":ddept", qro->value("drug_dept_code").toString());
        qrot->bindValue(":oper", pub::usr_code);
        qrot->bindValue(":drug_code", qro->value("drug_code").toString());
        qrot->bindValue(":grp", qro->value("group_code").toString());
        if(!qrot->exec()){
            QMessageBox::information(this,"error", "error in UPDATE PHA_COM_STORAGE "+qrot->lastError().text());
            qDebug()<<qrot->lastQuery();
            qDebug()<< qro->value("out_num").toInt() ;
            qDebug()<< qro->value("drug_storage_code").toString();
            qDebug()<< qro->value("drug_dept_code").toString();
            qDebug()<< pub::usr_code;
            qDebug()<< qro->value("drug_code").toString();
            qDebug()<< qro->value("group_code").toString();
            return;
        }
    }
qDebug()<<"pha_com_output";
    qro->prepare("update fin_opb_feedetail set CONFIRM_FLAG = '1',CONFIRM_CODE = :oper,CONFIRM_DEPT = :dept,"
                 " CONFIRM_DATE = sysdate, NOBACK_NUM = qty,CONFIRM_NUM = 0 "
                 " where  invoice_no = :ivno");
    qro->bindValue(":oper", pub::usr_code);
    qro->bindValue(":dept", deptCode);
qDebug()<<deptCode;
    qro->bindValue(":ivno", invo_no);
    if(!qro->exec()){
        QMessageBox::information(this,"error", "error in update fin_opb_feedetail "+qro->lastError().text());
        qDebug()<<qro->lastQuery();
        return;
    }
qDebug()<<"fin_opb_feedetail";
    sq = "UPDATE PHA_COM_OUTPUT SET RETURN_NUM = EXAM_NUM WHERE  RECIPE_NO in(" + recipe + ")";
    //qro->bindValue(":rcp", recipe);
    if(!qro->exec(sq)){
        QMessageBox::information(this,"error", "error in update pha_com_output "+qro->lastError().text());
        qDebug()<<qro->lastQuery();
        return;
    }
qDebug()<<qro->lastQuery();
qDebug()<<recipe;


qDebug()<<"PHA_COM_OUTPUT";
    qro->prepare("INSERT INTO pha_com_output ( DRUG_DEPT_CODE,OUT_BILL_CODE,SERIAL_CODE,GROUP_CODE,OUT_LIST_CODE,"
                 "OUT_TYPE,CLASS3_MEANING_CODE,IN_BILL_CODE,IN_SERIAL_CODE,IN_LIST_CODE,DRUG_CODE,TRADE_NAME,"
                 "DRUG_TYPE,DRUG_QUALITY,SPECS,PACK_UNIT,PACK_QTY,MIN_UNIT,SHOW_FLAG,SHOW_UNIT,BATCH_NO,VALID_DATE,"
                 "PRODUCER_CODE,COMPANY_CODE,RETAIL_PRICE,WHOLESALE_PRICE,PURCHASE_PRICE,OUT_NUM,SALE_COST,TRADE_COST,"
                 "APPROVE_COST,STORE_NUM,STORE_COST,SPECIAL_FLAG,OUT_STATE,APPLY_NUM,APPLY_OPERCODE,APPLY_DATE,"
                 "EXAM_NUM,EXAM_OPERCODE,EXAM_DATE,APPROVE_OPERCODE,APPROVE_DATE,PLACE_CODE,RETURN_NUM,DRUGED_BILL,"
                 "MED_ID,DRUG_STORAGE_CODE,RECIPE_NO,SEQUENCE_NO,GET_PERSON,MARK,OPER_CODE,OPER_DATE,ARK_FLAG"
                 ",ARK_BILL_CODE,OUT_DATE) "
                 " select  DRUG_DEPT_CODE,SEQ_PHA_OUTBILL_ID.NEXTVAL,1,GROUP_CODE,OUT_LIST_CODE,'M2','M2',IN_BILL_CODE,"
                 "IN_SERIAL_CODE,IN_LIST_CODE,DRUG_CODE,TRADE_NAME,DRUG_TYPE,DRUG_QUALITY,SPECS,PACK_UNIT,PACK_QTY,"
                 "MIN_UNIT,SHOW_FLAG,SHOW_UNIT,BATCH_NO,VALID_DATE,PRODUCER_CODE,COMPANY_CODE,RETAIL_PRICE,"
                 "WHOLESALE_PRICE,PURCHASE_PRICE,0-OUT_NUM,0-SALE_COST,TRADE_COST,0-APPROVE_COST,0,0,SPECIAL_FLAG,"
                 "OUT_STATE,OUT_NUM,:OPER_CODE,sysdate,0-EXAM_NUM,EXAM_OPERCODE,sysdate,:OPER_CODE,sysdate,PLACE_CODE,"
                 "0,DRUGED_BILL,MED_ID,DRUG_STORAGE_CODE,RECIPE_NO,SEQUENCE_NO,GET_PERSON,MARK,:OPER_CODE,sysdate,"
                 "ARK_FLAG,ARK_BILL_CODE,sysdate from pha_com_output where RECIPE_NO in(" + recipe + ")");
    qro->bindValue(":OPER_CODE", pub::usr_code);

    if(!qro->exec()){
        QMessageBox::information(this,"error", "error in INTO pha_com_output "+qro->lastError().text());
        qDebug()<<qro->lastQuery();
        qDebug()<<pub::usr_code<<recipe;
        return;
    }
qDebug()<<"insertPHA_COM_OUTPUT";

    ui->pbTf->setEnabled(false);
    ui->pbBldy->setEnabled(false);    //病历
    ui->pbSinglePrint->setEnabled(false);    //处方
    result= QMessageBox::warning(NULL, "注意", "退费完成，是否打印退费清单？",QMessageBox::Yes|QMessageBox::No);
    if(result == QMessageBox::No){
        return;
    }else{
        tfPrint();
    }

}

void Dialog_cfdy::tfPrint()
{

    QAxObject *excel;   //操作excel用于打印输出

    try{
        excel = new QAxObject("Excel.Application"); //
    }
    catch(...){
        try{
            excel = new QAxObject("et.Application"); //
        }
        catch(...){
            QMessageBox::information(this,"错误","电子表启动失败！");
            return;
        }
    }

    QString fileName = QCoreApplication::applicationDirPath();
    fileName.append("/tui.xls");

    //excel->dynamicCall("SetVisible (bool Visible)", "false"); // 设置为不显示窗体
    //excel->setProperty("DisplayAlerts", false); //不显示任何警告信息

    QAxObject *wkBooks = excel->querySubObject("Workbooks");
    QAxObject *book =  wkBooks->querySubObject("Open(const QString&)", fileName);
    QAxObject *wkSheets = book->querySubObject("Sheets");
    QAxObject *sheet = wkSheets->querySubObject("Item(int)", 1);
    QAxObject *cell  = new QAxObject ;

    //清空表格
    int x,y;
    for(x=6;x<11;x++){
        for(y=2;y<5;y++){
            cell = sheet->querySubObject("Cells(int, int)", x,  y);
            cell->setProperty("Value", "");
        }
    }
    x=6;
    y=2;

    //收据号关联的退费项目
    QString invo_no = pub::add0(ui->leSjh->text().trimmed(),12);
    qro->exec("select a.item_name trade_name , a.specs, a.price_unit pack_unit,  "
              " a.pqty qty, concat( concat(a.own_cost/a.pqty  ,'/'), a.price_unit) prs"
              " from view_feedetail a  where invoice_no = '" + invo_no + "'"
              " and qty >0 order by od ");

    QString tmpit;
    while(qro->next()){

        tmpit = qro->value("trade_name").toString();
        tmpit.append("("+qro->value("prs").toString()+")");
        cell=sheet->querySubObject("Cells(int, int)",x,y);
        cell->setProperty("Value",tmpit);
        y++;

        tmpit = qro->value("specs").toString();
        cell = sheet->querySubObject("Cells(int, int)",x,y);
        cell->setProperty("Value",tmpit);
        y++;

        tmpit=qro->value("qty").toString();
        tmpit = tmpit + qro->value("pack_unit").toString();
        cell = sheet->querySubObject("Cells(int, int)",x,y);
        cell->setProperty("Value",tmpit);
        y++;

        x ++ ;
        y = 2;
    }

    //患者姓名、就诊日期
    QString sq = "select name,to_char(reg_date,'yyyy-mm-dd') "
                 " from fin_opr_register where clinic_code = '"+ clinicCode +"'";
    qro->exec(sq);
    qro->next();
    tmpit = "患者:" + qro->value(0).toString() + "    发票号:" + invo_no;
    tmpit.append("    就诊日期:" + qro->value(1).toString());
    cell = sheet->querySubObject("Cells(int, int)", 3, 2);
    cell->setProperty("Value",tmpit);

    tmpit = "退药日期:" + QDate::currentDate().toString("yyyy-MM-dd");
    cell = sheet->querySubObject("Cells(int, int)",3,6);
    cell->setProperty("Value",tmpit);

    //收费类别、金额
    qro->exec("select pact_name, own_cost, pay_cost from fin_opb_invoiceinfo "
              "where invoice_no = '" + invo_no + "'");
    qro->next();
    double yb,xj;   //医保金额，现金金额
    yb = qro->value("pay_cost").toDouble();
    xj = qro->value("own_cost").toDouble();
    tmpit = qro->value("pact_name").toString();
    if(tmpit == "现金"){
        tmpit = tmpit + "，支付金额：" + QString::asprintf("%.2f", xj);
    }else{
        tmpit = "医保，卡：" +  QString::asprintf("%.2f", yb);
        tmpit = tmpit + "，现金："+QString::asprintf("%.2f", xj);
    }
    cell = sheet->querySubObject("Cells(int, int)",12,2);
    cell->setProperty("Value",tmpit);

    tmpit = "医生签字：" + doctName;
    cell = sheet->querySubObject("Cells(int, int)",12,3);
    cell->setProperty("Value",tmpit);
    book->dynamicCall("Save()");   //保存文件
    book->setProperty("ActivePrinter", cfPrinter);
    book->dynamicCall("PrintOut()");   //打印输出
    book->dynamicCall("PrintOut()");   //打印输出
    excel->dynamicCall("Quit()"); // 关闭excel
    book->dynamicCall("Close(Boolean)", false);  // 关闭文件

    QMessageBox::information(this,"注意","打印输出完毕！");

}

void Dialog_cfdy::on_rbF_clicked()
{
    ui->leSjh->clear();
    ui->lwYfy->clear();
    ui->pbTf->setEnabled(false);
    ui->pbBldy->setEnabled(false);
    ui->pbSinglePrint->setEnabled(false);    //处方
    ui->leSjh->setFocus();
}

void Dialog_cfdy::on_rbB_clicked()
{
    ui->leSjh->clear();
    ui->lwYfy->clear();
    ui->pbTf->setEnabled(false);
    ui->pbBldy->setEnabled(false);
    ui->pbSinglePrint->setEnabled(false);    //处方
    ui->leSjh->setFocus();
}


void Dialog_cfdy::on_pbBldy_clicked()
{
    ui->pbBldy->setEnabled(false);
    ui->pbSinglePrint->setEnabled(false);    //处方
    qApp->processEvents();
    QMap<QString, QString> pageInfo;
    QString bzAtinc;

    if(clinicCode.isEmpty()){
        QMessageBox::information(this,"注意","clinicCode 为空，无法检索病历!");
        return;
    }
    QString sq;
    sq = "select name, sex_code, to_char(birthday,'yyyyMMdd') birth,to_char( reg_date,'yyyy-mm-dd')reg_dt, "
         "dept_name, mcard_no , card_no "
         " from fin_opr_register"
         " where clinic_code = '" + clinicCode + "'";
    qro->exec(sq);
    qro->next();
    pageInfo["name"] = qro->value(0).toString();
    pageInfo["sex"] = qro->value(1).toString() == "M" ? "男" : "女";
    pageInfo["birth"] = qro->value(2).toString() ;
    pageInfo["regdt"] = qro->value(3).toString() ;
    pageInfo["dpnm"] = qro->value(4).toString() ;
    pageInfo["mcard_no"] = qro->value(5).toString() ;
    pageInfo["card_no"] = qro->value(6).toString() ;

    qDebug()<<"检索医师处方内容";
    QString  cur_date, cur_bzh;
    sq="select FEE_CODE,recipe_no,charge_flag,CLINIC_CODE,CARD_NO,to_char(REG_DATE,'yyyy-mm-dd') cdt ,ITEM_CODE,ITEM_NAME,"
       "SPECS,DRUG_FLAG,CLASS_CODE,QTY,ITEM_UNIT,ONCE_DOSE,ONCE_UNIT,FREQUENCY_NAME,USAGE_NAME,EXEC_DPNM,DOCT_NAME,LAB_TYPE,"
       "CHECK_BODY,CLINICDIAG_CODE,CLINICDIAG_NAME,CLINICOTHERDIAG1_CODE,CLINICOTHERDIAG1_NAME,CLINICOTHERDIAG2_CODE,"
       "CLINICOTHERDIAG2_NAME from met_ord_recipedetail where clinic_code='" + clinicCode + "'"
       " order by drug_flag, oper_date";
    if(!qro->exec(sq)){
        QMessageBox::information(this,"error", qro->lastError().text());
        qDebug()<<qro->lastError().text();
        qDebug()<<qro->lastQuery();
        return;
    }
    if(!qro->next()){
        QMessageBox::information(this,"error", "找不到指定检索信息关联的医师处方内容！");
        qDebug()<<qro->lastQuery();
        return;
    }
    pageInfo["cur_date"] = qro->value("cdt").toString();
    pageInfo["cur_bzh"] = qro->value("CARD_NO").toString();
    pageInfo["jzys"] = qro->value("DOCT_NAME").toString();

    while(true){
        //首先检查处方是否执行，然后检查是否退费
        pageInfo["zd"] = qro->value("CLINICDIAG_NAME").toString();
        if(!qro->value("CLINICOTHERDIAG1_NAME").toString().isEmpty()){
            pageInfo["zd"].append("^"+qro->value("CLINICOTHERDIAG1_NAME").toString());
        }
        if(!qro->value("CLINICOTHERDIAG2_NAME").toString().isEmpty()){
            pageInfo["zd"].append("^"+qro->value("CLINICOTHERDIAG2_NAME").toString());
        }
        QString s;
        s = qro->value("charge_flag").toString();
        if(s == "0"){
            s = "（未执行）";
        }else{
            sq=" select count(*) c from pha_com_output where recipe_no = "
               "'"+qro->value("recipe_no").toString()+"' and return_num >0";
            qrot->exec(sq);
            qrot->next();
            if(qrot->value(0).toInt() > 0){
                s = "（已退费）";
            }else{
                s = "";
            }
        }
        int fee_code = qro->value("fee_code").toInt();
        //1 西药 ， 2 中药
        //4 化验 ，7 检查
        //5 处置，
        // 6 留观费 ，10 器械
        //11 采血费， 12 彩色打印照片, 14 取暖费 ，22 床位费（床）

        if( fee_code == 1 || fee_code == 2){ //药品
            s.append(qro->value("ITEM_NAME").toString());
            s.append(" ");
            s.append(qro->value("SPECS").toString());
            s.append(qro->value("QTY").toString());
            s.append(qro->value("ITEM_UNIT").toString());
            s.append("  ");
            s.append(qro->value("USAGE_NAME").toString());
            s.append(" ");
            s.append(qro->value("ONCE_DOSE").toString());
            s.append(qro->value("ONCE_UNIT").toString());
            s.append("/");
            s.append(qro->value("FREQUENCY_NAME").toString());
            if(pageInfo["cljg"].isEmpty()){
                pageInfo["cljg"].append(s);
            }else{
                pageInfo["cljg"].append("\r\n" + s);
            }
        }else if( fee_code == 4 || fee_code == 7){ //化验，检查
            s.append(qro->value("ITEM_NAME").toString());
            s.append(" ");
            s.append(qro->value("QTY").toString());
            s.append(qro->value("ITEM_UNIT").toString());
            if(pageInfo["jcjg"].isEmpty()){
                pageInfo["jcjg"].append(s);
            }else{
                pageInfo["jcjg"].append("\r\n" + s);
            }
        }else if( fee_code == 5){ //处置
            s.append(qro->value("ITEM_NAME").toString());
            s.append(" ");
            s.append(qro->value("QTY").toString());
            s.append(qro->value("ITEM_UNIT").toString());
            if(pageInfo["cljg"].isEmpty()){
                pageInfo["cljg"].append(s);
            }else{
                pageInfo["cljg"].append("\r\n" + s);
            }
        }

        if(!qro->next()){
            break;
        }
    }

    sq="select r.hzzs,r.xbs,r.jws,r.tgjc,r.yz,r.ys ,r.atinc , l.xmmc, l.xmjg, p.lxdh "
       "from ys_bz_e_rec r, ys_bz_e_main m, ys_bz_e_lib l, ys_bz_e_patient_info p"
       " where m.atinc = r.id and  r.rq='"+pageInfo["cur_date"]+"' and m.bzh='"+pageInfo["cur_bzh"]+"'"
       " and l.id=r.id and m.patient_id=p.atinc";

    qrm->exec(sq);

    if(!qrm->next()){
        bzAtinc = "";
        pageInfo["hzzs"] = "";
        pageInfo["xbs"] = "";
        pageInfo["jws"] = "";
        pageInfo["zzms"] = "";
        pageInfo["yz"] = "";

    }else{
        bzAtinc = qrm->value("atinc").toString();
        pageInfo["hzzs"] = qrm->value("hzzs").toString();
        pageInfo["xbs"] = qrm->value("xbs").toString();
        pageInfo["jws"] = qrm->value("jws").toString();
        pageInfo["zzms"] = qrm->value("tgjc").toString();
        pageInfo["yz"] = qrm->value("yz").toString();
        pageInfo["lxdh"] = qrm->value("lxdh").toString();
    }

    QString item;
    QString fileName;
    //QString fileName = QCoreApplication::applicationDirPath();
    //fileName.append("/bz.doc");
    fileName.append("c:/bz.doc");

    QAxObject *m_WordFile;   //操作 word 用于打印输出

    m_WordFile = new QAxObject();//取代QAxWidget，使其在子线程中可用
    bool bFlag = m_WordFile->setControl( "word.Application" );
    if(NULL == m_WordFile)
    {
        // 尝试用wps打开
        bFlag = m_WordFile->setControl( "kwps.Application" );
        if(!bFlag)
        {
            QMessageBox::information(this,"错误","Office 文档系统启动失败！");
            return ;
        }
    }

    m_WordFile->setProperty("Visible", false);
    //m_WordFile->setProperty("Visible", true);
    // 获取所有的工作文档
    QAxObject *Documents = m_WordFile->querySubObject("Documents");
    if(NULL == Documents)
    {
        QMessageBox::information(this,"错误","Can't retreive Documents！");
        return ;
    }
    // 新建一个文档
    Documents->dynamicCall("Add()");

    // 获取当前激活的文档
    QAxObject *m_Document = m_WordFile->querySubObject("ActiveDocument");
    QAxObject *my_tst = m_Document->querySubObject("pagesetup");
    QAxObject *word_select = m_WordFile->querySubObject("Selection");


    word_select->querySubObject("Font")->setProperty("Size", 18);
    word_select->querySubObject("Font")->setProperty("Name", "黑体");
    word_select->querySubObject("ParagraphFormat")->setProperty("Alignment", 1);
    item="门诊病历\n";
    word_select->dynamicCall("TypeText(const string)", item);

    word_select->querySubObject("Font")->setProperty("Size", 12);
    word_select->querySubObject("ParagraphFormat")->setProperty("Alignment", 0);

    word_select->querySubObject("Font")->setProperty("Name", "宋体");
    word_select->dynamicCall("TypeText(const string)", "姓名：");
    word_select->querySubObject("Font")->setProperty("Name", "楷体");
    word_select->dynamicCall("TypeText(const string)", pageInfo["name"]);

    word_select->querySubObject("Font")->setProperty("Name", "宋体");
    word_select->dynamicCall("TypeText(const string)", "\t\t性别：");
    word_select->querySubObject("Font")->setProperty("Name", "楷体");
    word_select->dynamicCall("TypeText(const string)", pageInfo["sex"]);

    word_select->querySubObject("Font")->setProperty("Name", "宋体");
    word_select->dynamicCall("TypeText(const string)", "\t\t年龄：");
    word_select->querySubObject("Font")->setProperty("Name", "楷体");
    QStringList ageList = pub::getNl(pageInfo["birth"]);
    word_select->dynamicCall("TypeText(const string)", ageList[0]+ageList[1]);

    word_select->querySubObject("Font")->setProperty("Name", "宋体");
    word_select->dynamicCall("TypeText(const string)", "\t\t病志号：");
    word_select->querySubObject("Font")->setProperty("Name", "楷体");
    word_select->dynamicCall("TypeText(const string)", pageInfo["card_no"]);

    word_select->querySubObject("Font")->setProperty("Name", "宋体");
    word_select->dynamicCall("TypeText(const string)", "\n就诊日期：");
    word_select->querySubObject("Font")->setProperty("Name", "楷体");
    word_select->dynamicCall("TypeText(const string)", pageInfo["regdt"]);

    word_select->querySubObject("Font")->setProperty("Name", "宋体");
    word_select->dynamicCall("TypeText(const string)", "\t\t诊室：");
    word_select->querySubObject("Font")->setProperty("Name", "楷体");
    word_select->dynamicCall("TypeText(const string)", pageInfo["dpnm"]);

    word_select->querySubObject("Font")->setProperty("Name", "宋体");
    word_select->dynamicCall("TypeText(const string)", "\t\t医保卡号：");
    word_select->querySubObject("Font")->setProperty("Name", "楷体");
    word_select->dynamicCall("TypeText(const string)", pageInfo["mcard_no"]);


    word_select->dynamicCall("TypeText(const string)", "\n");
    item="- - - - - ";
    for(int cn = 0; cn < 7 ; cn++){
        word_select->dynamicCall("TypeText(const string)", item);
    }
    item = item+"\n";

    word_select->querySubObject("Font")->setProperty("Name", "宋体");
    word_select->dynamicCall("TypeText(const string)", "\n患者主诉：\n");
    word_select->querySubObject("Font")->setProperty("Name", "楷体");
    word_select->dynamicCall("TypeText(const string)", pageInfo["hzzs"]);

    word_select->querySubObject("Font")->setProperty("Name", "宋体");
    word_select->dynamicCall("TypeText(const string)", "\n现病史：\n");
    word_select->querySubObject("Font")->setProperty("Name", "楷体");
    word_select->dynamicCall("TypeText(const string)", pageInfo["xbs"]);

    word_select->querySubObject("Font")->setProperty("Name", "宋体");
    word_select->dynamicCall("TypeText(const string)", "\n既往史：\n");
    word_select->querySubObject("Font")->setProperty("Name", "楷体");
    word_select->dynamicCall("TypeText(const string)", pageInfo["jws"]);

    word_select->querySubObject("Font")->setProperty("Name", "宋体");
    word_select->dynamicCall("TypeText(const string)", "\n专科检查：\n");
    word_select->querySubObject("Font")->setProperty("Name", "楷体");
    word_select->dynamicCall("TypeText(const string)", pageInfo["zzms"]);

    word_select->querySubObject("Font")->setProperty("Name", "宋体");
    word_select->dynamicCall("TypeText(const string)", "\n化验检查：\n");
    word_select->querySubObject("Font")->setProperty("Name", "楷体");
    word_select->dynamicCall("TypeText(const string)", pageInfo["jcjg"]);
    word_select->dynamicCall("TypeText(const string)", pageInfo["jcjg0"]);
    word_select->querySubObject("Font")->setProperty("Name", "宋体");
    word_select->dynamicCall("TypeText(const string)", "\n诊断：\n");
    word_select->querySubObject("Font")->setProperty("Name", "楷体");
    item = pageInfo["zd"];
    item.replace("^","，");
    word_select->dynamicCall("TypeText(const string)", item);

    word_select->querySubObject("Font")->setProperty("Name", "宋体");
    word_select->dynamicCall("TypeText(const string)", "\n处置：\n");
    word_select->querySubObject("Font")->setProperty("Name", "楷体");
    word_select->dynamicCall("TypeText(const string)", pageInfo["cljg"]);

    word_select->querySubObject("Font")->setProperty("Name", "宋体");
    word_select->dynamicCall("TypeText(const string)", "\n\t\t\t\t\t\t\t\t\t\t\t主治医生：");
    word_select->querySubObject("Font")->setProperty("Name", "楷体");
    word_select->dynamicCall("TypeText(const string)", pageInfo["jzys"]);

    m_Document->querySubObject("ActiveWindow")->querySubObject("ActivePane")
            ->querySubObject("View")->setProperty("SeekView", 9 );//显示页眉 wdSeekCurrentPageHeader

    word_select->dynamicCall("TypeText(const string)", pub::hos_name);

    //wdAlignParagraphRight:右边对齐;
    //wdAlignParagraphJustify:两边对齐;
    //wdAlignParagraphLeft:左边对齐;
    //wdAlignParagraphCenter:中间对齐;

    /*
    wdSeekCurrentPageFooter 	10 	当前页页脚。
    wdSeekCurrentPageHeader 	9 	当前页页眉。
    wdSeekEndnotes 	8 	尾注。
    wdSeekEvenPagesFooter 	6 	偶数页页脚。
    wdSeekEvenPagesHeader 	3 	偶数页页眉。
    wdSeekFirstPageFooter 	5 	首页页脚。
    wdSeekFirstPageHeader 	2 	首页页眉。
    wdSeekFootnotes 	7 	脚注。
    wdSeekMainDocument 	0 	主文档。
    wdSeekPrimaryFooter 	4 	主页脚。
    wdSeekPrimaryHeader 	1 	主页眉。
    */

    m_Document->querySubObject("ActiveWindow")->querySubObject("ActivePane")
            ->querySubObject("View")->setProperty("SeekView",10 );//显示页脚wdSeekCurrentPageFooter

    item="打印时间：";
    QDateTime c;
    if(!bzAtinc.isEmpty()){

        qrm->exec("update ys_bz_e_rec set dybz = dybz + 1 where atinc = " + bzAtinc);
        qrm->exec("select dybz from ys_bz_e_rec where atinc = " + bzAtinc);
        qrm->next();

        item=item + c.currentDateTime().toString("yyyy/MM/dd hh:mm:ss");
        item=item+"\t 第 "+qrm->value(0).toString()+" 次打印";
    }else{
        item = item + c.currentDateTime().toString("yyyy/MM/dd hh:mm:ss");
        item = item + "\t *数据过渡期间记录不完整*";//+DateTimePicker2->Date.DateString()+"        ";

    }

    item=item+"\t 此病历经医生签字后生效";
    word_select->dynamicCall("TypeText(const string)", item);

    m_Document->dynamicCall("SaveAs (const QString&)", fileName);
    m_WordFile->setProperty("ActivePrinter", bzPrinter);
    m_Document->dynamicCall("PrintOut()");

    m_Document->dynamicCall("Close (boolean)", true);  //关闭文本窗口
    m_WordFile->dynamicCall("Quit(void)");  //退出word

}

void Dialog_cfdy::on_rbX_clicked()
{
    ui->leSjh->clear();
    ui->lwYfy->clear();
    ui->pbTf->setEnabled(false);
    ui->pbBldy->setEnabled(false);
    ui->pbSinglePrint->setEnabled(false);    //处方
    ui->leSjh->setFocus();
}
